<template>
  <div v-if="showPage" class="garageBox">
    <c-title :hide="false" :text="pageTitle"></c-title>
    <template v-if="carList.length != 0">
   
   <div v-for="(item, index) in carList" :key="item.id" class="garageItemBox" @click="goMyloveCar(item)">
    <div class="garageItemTop">
      <div class="garageItemTopL">
        <img src="../../assets/images/carImg/carLogo.png" class="carLogo"/>
        <div class="carNumber">{{item.cph}}</div>
      </div>
      <div class="garageItemTopR">
        <div class="carName">{{item.brand_name}} {{item.series_name}} <span v-if="item.is_default == 1" class="tag">当前</span></div>
        <div class="carXinghao">{{item.nf}}款 {{item.pl}} {{item.gearbox}} {{item.version}}</div>
      </div>
    </div>
    <div class="garageItemBottom">
      <div class="setDefault" v-if="item.is_default == 1" style="background-color: #ddd;">已设为默认</div>
      <div class="setDefault" @click.stop="setDefault(item.id)" v-if="item.is_default == 2">设为默认</div>
      <div class="delete" @click.stop="deletecar(item.id)">删除</div>
    </div>
   </div>
    </template>
    <template v-else>
      <div class="nocardata">暂无车辆赶快去添加您的爱车吧~</div>
    </template>
   <div class="addcarbtn" @click="addCar">
      新增车型
    </div>
    <van-popup class="vinpopupBox" v-model="showvinpopup">
      <div class="vinpopup">
        <div class="title">添加车架号</div>
        <div class="vininputbox">
          <div class="vininputboxL">
            <van-field v-model="vinvalue" placeholder="请输入17位VIN车架号" class="vininput" />
          </div>
          <div class="vininputboxR">
            <img src="../../assets/images/carImg/saoyisao.png" class="saoyisao" @click="opWithPermission"/>
            <input v-if="showInputFile" type="file" accept="image/*" ref="imgFile" id="fileInput" class="cameraInput" name="file" @change="handleCamera($event)"/>
          </div>
        </div>
        <div class="vinbtnbox">
          <div class="vinbtnstyle" style="color: #333;border-right: 1px solid #f0f0f0;" @click="cancelvinpopup">取消</div>
          <div class="vinbtnstyle" @click="goPerfectCar">确定</div>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script>
import {
  Toast,
  Dialog
} from 'vant';
import cTitle from "components/title";
export default {
  data() {
    return {
      showInputFile:false,
      showvinpopup:false,
      carList:[],
      showPage:false,
      vinvalue:'',
      pageTitle:''
    };
  },
  created(){
    // this.getcarlist()
  },
  mounted() {
    
  },
  activated() {
    if(window.localStorage.getItem('filePower')){
      this.showInputFile = true
    } else {
      this.showInputFile = false
    }
    this.vinvalue = ''
    this.pageTitle = this.$route.query.title || "我的爱车";
    this.fun.setWXTitle(this.pageTitle);
    this.getcarlist()
  },
  deactivated() {
   
  },
  // beforeRouteLeave(to, from, next) {
    
  // },
  methods: {
    goMyloveCar(item){
      window.localStorage.setItem('member_id',item.member_id);
      this.$router.push(this.fun.getUrl('myloveCar',{},{}));
    },
    handleCamera(event) {
      const _this = this
      const reader = new FileReader();
      // 文件读取完毕后的处理函数
      reader.onload = function(event) {
        const base64 = event.target.result;
        _this.getCarOcr(base64)
      };
      reader.readAsDataURL(event.target.files[0]);
    },
    getCarOcr(imgdata){
			let base64Arr = imgdata.split(',')
			let url = "car.vinOcr";
      let json = { image_base64: this.encodeBase64(base64Arr[1]) };
      $http.post(url, json, "loading").then(response => {
        console.log(response)
        if(response.result==1){
          document.getElementById('fileInput').value = '';
          this.vinvalue = response.data.vin
        } else {
          document.getElementById('fileInput').value = '';
          Toast(response.msg);
        }
      })	
		},
    encodeBase64(data) {
      return encodeURIComponent(data);
    },
    pictCallback(ret){
      const list = ret.list;
      for(let i in list){
        if(list[i].name == 'camera'){
          if(list[i].granted == 'true' || list[i].granted == true){
            this.showInputFile = true
            window.localStorage.setItem('filePower',true)
          }
        }
      }
    },
    apialert(_msg, callback){
      api.alert({
          title: '提示',
          msg: _msg,
      }, function(ret, err) {
        if(callback){
          callback();
        }
      });
    },
    opWithPermission(){
      const _this = this
      if(!_this.confirmPer('camera')){
        return;
      }
      api.getPicture({
          sourceType: 'camera',
          mediaValue: 'pic',
          destinationType: 'url',
      }, function(ret, err) {
          if (ret) {
            _this.apialert(JSON.stringify(ret));
          } else {
            _this.apialert(JSON.stringify(err));
          }
      });
    },
    confirmPer(perm){
      const _this = this
      const has = _this.hasPermission(perm);
      if(!has || !has[0] || !has[0].granted){
        api.confirm({
          title: '提醒',
          msg: '没有获得 ' + perm + " 权限\n是否前往设置？",
          buttons: ['去设置', '取消']
        }, function(ret, err) {
          if(1 == ret.buttonIndex){
            _this.reqPermission(perm,_this.pictCallback);
          }
        });
        return false;
      }
      return true;
	  },
    hasPermission(one_per){
      const _this = this
      const perms = new Array();
	    	perms.push(one_per);
        const rets = api.hasPermission({
          list:perms
        });
        if(!one_per){
          console.log('判断结果：' + JSON.stringify(rets));
          return;
        }
        return rets;
    },
    reqPermission(one_per, callback){
      const _this = this
      const perms = new Array();
      if(one_per){
        perms.push(one_per);
      }
      api.requestPermission({
        list: perms,
        code: 100001
      }, function(ret, err){
        if(callback){
          callback(ret);
          return;
        }
        var str = '请求结果：\n';
        str += '请求码: ' + ret.code + '\n';
        str += "是否勾选\"不再询问\"按钮: " + (ret.never ? '是' : '否') + '\n';
        str += '请求结果: \n';
        var list = ret.list;
        for(var i in list){
          str += list[i].name + '=' + list[i].granted + '\n';
        }
        _this.apialert(str);
        console.log(JSON.stringify(ret));
      });
    },
    setDefault(id){
      let url = "car.personalCarSetDefault";
      let json = {
        id:id,
        is_default:1,
        member_id:window.localStorage.getItem('member_id')
      };
      $http.post(url, json, "loading").then(response => {
        console.log(response)
        if(response.result==1){
          this.getcarlist()
        } else {
          Toast(response.msg);
        }
      })
    },
    deletecar(id){
      let url = "car.personalCarDelete";
      let json = {
        id:id,
        is_delete:1,
        member_id:window.localStorage.getItem('member_id')
      };
      Dialog.confirm({
        title: '提示',
        message: '您确定要删除该车辆？',
      })
      .then(() => {
        $http.post(url, json, "loading").then(response => {
          console.log(response)
          if(response.result==1){
            this.getcarlist()
          } else {
            Toast(response.msg);
          }
        })
      })
      .catch(() => {
        // on cancel
      });
      
    },
    addCar(){
      this.showvinpopup = true
    },
    cancelvinpopup(){
      this.vinvalue = ''
      this.showvinpopup = false
    },
    getcarlist(){
      const _this = this
      let url = "car.personalCarList";
      let json = {
        member_id:window.localStorage.getItem('member_id')
      };
      $http.post(url, json, "loading").then(response => {
        console.log(response)
        if(response.result==1){
          this.carList = response.data
          setTimeout(function(){
            _this.showPage = true
          },100)
          if(this.carList.length != 0){
            let onoff = false;
            this.carList.forEach((item)=>{
              if(item.is_default == 1){
                onoff = true
                window.localStorage.setItem('defaultCarData', JSON.stringify(item));
              }
            })
            if(!onoff){
              this.setDefault(this.carList[0].id)
            }
          } else {
            window.localStorage.setItem('defaultCarData', '');
          }
        } else {
          Toast(response.msg);
        }
      })
    },
    goPerfectCar(){
      console.log(this.vinvalue)
      if(!this.vinvalue){
        Toast('请填写车架号');
        return false
      }
      let url = "car.vinQuery";
      let json = { vin: this.vinvalue };
      $http.post(url, json, "loading").then(response => {
        console.log(response)
        if(response.result==1){
          window.sessionStorage.setItem('carData', JSON.stringify(response.data));
          this.showvinpopup = false
          this.$router.push(this.fun.getUrl("perfectCar", {}, {back:2}));
        } else {
          Toast(response.msg);
        }
      })
    },
  },
  components: {
    cTitle
  }
};

</script>

<style lang="scss" rel="stylesheet/scss" scoped>
 
 .garageBox{
  width: 100%;
  height: 100vh;
  background: #f5f5f5;
  padding: 0.75rem;
  box-sizing: border-box;
  .nocardata{
    font-size: 0.875rem;
    text-align: center;
    color: #333;
    margin-top:10rem;
  }
  .addcarbtn{
    width: 90%;
    height: 2.5rem;
    background: #FB1622;
    border-radius: 0.5rem;
    margin-top:1.5rem;
    font-weight: 500;
    font-size: 0.875rem;
    color: #FFFFFF;
    line-height:2.5rem;
    text-align: center;
    position: fixed;
    left:5%;
    bottom:1rem;
  }
  .garageItemBox{
    width: 100%;
    height: 8rem;
    padding: 0.5rem;
    box-sizing: border-box;
    background: linear-gradient( 324deg, rgba(255,255,255,0.68) 0%, rgba(255,255,255,0.5) 100%);
    box-shadow: 0px 1px 24px -1px rgba(0,0,0,0.01);
    border-radius: 0.5rem;
    border: 1px solid rgba(255,255,255,0.6);
    position: relative;
    margin-bottom: 0.75rem;
    .garageItemTop{
      .garageItemTopL{
        width: 4rem;
        height: 4rem;
        float: left;
        .carLogo{
          width: 2rem;
          height: 2rem;
          display: block;
          margin:0.65rem auto 0;
        }
        .carNumber{
          font-size: 0.75rem;
          color: #999;
          text-align: center;
        }
      }
      .garageItemTopR{
        margin-left:4rem;
        padding-left: 1rem;
        overflow: hidden;
        .carName{
          font-size: 1rem;
          font-weight: bold;
          text-align: left;
          margin-top: 0.8rem;
          .tag{
            display: inline-block;
            width: 1.5rem;
            height: 0.8rem;
            font-size: 0.5rem;
            line-height: 0.8rem;
            background: #FBB9B6;
            text-align: center;
            border-radius: 0.125rem;
            position: relative;
            top: -0.2rem;
            color: #FB1622;
          }
        }
        .carXinghao{
          font-size: 0.75rem;
          color: #999;
          text-align: left;
          margin-top: 0.54rem;
        }
      }
    }
    .garageItemBottom{
      width: 100%;
      height: 2.5rem;
      position: absolute;
      left:0;
      bottom:0;
      .delete{
        width: auto;
        padding: 0 0.8rem;
        line-height: 1.6rem;
        margin-top:0.3125rem;
        float: right;
        font-size: 0.75rem;
        text-align: center;
        color: #fff;
        background: #FB1622;
        border-radius: 1.875rem;
        box-sizing: border-box;
        margin-right: 1rem;
      }
      .setDefault{
        width: auto;
        padding: 0 0.5rem;
        line-height: 1.6rem;
        margin-top:0.3125rem;
        float: right;
        font-size: 0.75rem;
        text-align: center;
        color: #fff;
        background: #FB1622;
        border-radius: 1.875rem;
        box-sizing: border-box;
        margin-right: 1rem;
      }
    }
  }
  .vinpopupBox{
  width: 80.8%;
  height: 11.5rem;
  border-radius: 0.5rem;
  .vinpopup{
    width: 100%;
    height: 100%;
    overflow: hidden;
    position: relative;
    .title{
      font-weight: 500;
      font-size: 1rem;
      color: #1F2329;
      line-height: 1.375rem;
      text-align: center;
      margin-top:1.5rem;
    }
    .vininputbox{
      width: 16.5rem;
      height: 2.5rem;
      margin:1.5rem auto 0;
      .vininputboxL{
        width: 13.4375rem;
        height:100%;
        border-radius: 4px;
        border: 1px solid #BFBFBF;
        box-sizing: border-box;
        float: left;
        .vininput{
          padding: 0;
          line-height: 2rem;
          margin-top:0.25rem;
          font-size: 0.875rem;
          padding-left: 0.5rem;
        }
      }
      .vininputboxR{
        width: 2.5rem;
        height: 2.5rem;
        background: #FB1622;
        border-radius: 0.5rem;
        float: right;
        position: relative;
        .saoyisao{
          width: 1.5rem;
          height: 1.5rem;
          display: block;
          margin: 0.5rem auto 0;
        }
        .cameraInput{
          width: 100%;
          height: 100%;
          position: absolute;
          left:0;
          top:0;
          z-index: 1;
          font-size: 0;
          opacity: 0;
        }
      }
    }
    .vinbtnbox{
      width: 100%;
      height: 3.125rem;
      position: absolute;
      left:0;
      bottom:0;
      border-top: 1px solid #F0F0F0;
      .vinbtnstyle{
        width: 50%;
        height: 100%;
        float: left;
        font-weight: 500;
        font-size:1rem;
        color: #FB1622;
        line-height: 3.125rem;
        text-align: center;
        box-sizing: border-box;
      }
    }
  }
 }
 }
 
</style>
